package com.gitee.empty_null.authorization.provider;

import com.gitee.empty_null.authorization.utils.OAuth2ConfigurerUtils;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.oauth2.core.OAuth2Token;
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService;
import org.springframework.security.oauth2.server.authorization.token.OAuth2TokenGenerator;

import java.util.ArrayList;
import java.util.List;

/**
 * @author xuhainan
 * @date 2024/1/16 13:38
 * @region hefei
 */
public class OAuth2AuthenticationProviderManager {

    private OAuth2AuthenticationProviderManager() {
    }

    public static List<AuthenticationProvider> createAuthenticationProviders(HttpSecurity httpSecurity, UserDetailsService userDetailsService) {
        List<AuthenticationProvider> authenticationProviders = new ArrayList<>();

        OAuth2AuthorizationService authorizationService = OAuth2ConfigurerUtils.getAuthorizationService(httpSecurity);
        OAuth2TokenGenerator<? extends OAuth2Token> tokenGenerator = OAuth2ConfigurerUtils.getTokenGenerator(httpSecurity);
        SessionRegistry sessionRegistry = httpSecurity.getSharedObject(SessionRegistry.class);

        OAuth2UsernamePasswordAuthenticationProvider usernamePasswordAuthenticationProvider =
                new OAuth2UsernamePasswordAuthenticationProvider(authorizationService, tokenGenerator, userDetailsService);
        if (sessionRegistry != null) {
            usernamePasswordAuthenticationProvider.setSessionRegistry(sessionRegistry);
        }
        authenticationProviders.add(usernamePasswordAuthenticationProvider);

        return authenticationProviders;
    }
}
